<!--  -->
<template>
  <div>
    <div class="pdf-viewer-container">
            <div class="pdf-viewer">
                <div class="viewer-header">
                    <div class="document-info">
                        <i class="fas fa-file-pdf"></i>
                        <span>{{ pdfTitle }}</span>
                    </div>
                    <div class="controls">
                        <button class="control-btn" @click="toggleThumbnails">
                            <i :class="showThumbnails ? 'fas fa-eye-slash' : 'fas fa-eye'"></i>
                            {{ showThumbnails ? '隐藏缩略图' : '显示缩略图' }}
                        </button>
                        <button class="control-btn" @click="printPdf">
                    <i class="fas fa-print"></i>
                    打印文档
                </button>
                        <div class="zoom-controls">
                            <button class="zoom-btn" @click="zoomOut" title="缩小">
                                <i class="fas fa-search-minus">-</i>
                            </button>
                            <button class="zoom-btn" @click="zoomIn" title="放大">
                                <i class="fas fa-search-plus"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="main-content">
                    <div class="thumbnails" :class="{ hidden: !showThumbnails }">
                        <div 
                            v-for="page in totalPages" 
                            :key="page"
                            class="thumbnail-item"
                            :class="{ 'active': page === currentPage }"
                            @click="jumpToPage(page)"
                        >
                            <canvas :ref="el => { if (el) thumbnailRefs[page-1] = el }"></canvas>
                        </div>
                    </div>
                    
                    <div class="pdf-pages-container" ref="pdfContainer" @scroll="handleScroll">
                        <div v-if="loading" class="loading-overlay">
                            <div class="spinner"></div>
                            <div class="loading-text">正在加载文档，请稍候...</div>
                        </div>
                        
                        <div 
                            v-for="page in renderedPages" 
                            :key="page"
                            class="pdf-page"
                            :style="{ width: pageWidth + 'px' }"
                        >
                            <div class="page-number">第 {{ page }} 页</div>
                            <canvas :ref="el => { if (el) pageRefs[page-1] = el }"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="status-bar">
                    <div>当前页面: {{ currentPage }} / {{ totalPages }}</div>
                    <div>缩放: {{ Math.round(scale * 100) }}%</div>
                    <div>总页数: {{ totalPages }}</div>
                </div>
            </div>
        </div>
        
        <div class="scroll-indicator" v-if="!loading">
            <i class="fas fa-book"></i>
            <div class="progress-container">
                <div class="progress-bar" :style="{ width: scrollProgress + '%' }"></div>
            </div>
            <span>已浏览 {{ scrollProgress }}%</span>
        </div>
  </div>
</template>
<script lang='ts' setup>

//参考网址 https://blog.csdn.net/qq_59344127/article/details/144950702
// 安装 npm i pdfjs-dist 不是

import { reactive,toRefs,ref,onMounted,watch} from 'vue'
import * as pdfjsLib from 'pdfjs-dist';

// 设置本地 worker 的路径
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdfjs/pdf.worker.min.js'; // 确保路径正确

const pdfContainer:any = ref(null);
const thumbnailRefs = ref<any[]>([]);
const pageRefs = ref<any[]>([]);
const currentPage = ref(1);
const totalPages = ref(0);
const loading = ref(true);
const showThumbnails = ref(true);
const scale = ref(1.2);
const scrollProgress = ref(0);
const pdfTitle = ref('演示文档.pdf');
const renderedPages:any = ref([]);
const pageWidth = ref(800);
let pdfDoc:any = null;
let pageHeights:any  = [];
let totalHeight = 0;
let viewportHeight = 0;

const loadPdf = async () => {
  try {
    const pdfUrl = 'http://123.57.237.81:8080/caresystem/upload/2025/7/11/20250711141043499.pdf';
    const loadingTask = pdfjsLib.getDocument(pdfUrl);
    pdfDoc = await loadingTask.promise;
    totalPages.value = pdfDoc.numPages;
    await renderAllPages();
    await renderThumbnails();
    loading.value = false;
  } catch (error) {
    console.error('加载PDF失败:', error);
    loading.value = false;
  }
};

const renderAllPages = async () => {
  renderedPages.value = Array.from({ length: totalPages.value }, (_, i) => i + 1);
  
  // 等待DOM更新
  await nextTick();
  
  let currentTop = 0;
  pageHeights = [];
  
  for (let i = 1; i <= totalPages.value; i++) {
    try {
      const page = await pdfDoc.getPage(i);
      const viewport = page.getViewport({ scale: scale.value });
      
      if (pageRefs.value[i-1]) {
        const canvas:any = pageRefs.value[i-1];
        const context = canvas.getContext('2d');
        
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        pageWidth.value = viewport.width;
        
        await page.render({
          canvasContext: context,
          viewport: viewport
        }).promise;
        
        pageHeights.push({
          page: i,
          top: currentTop,
          height: viewport.height
        });
        
        currentTop += viewport.height + 20; // 20px 页间距
      }
    } catch (error) {
      console.error(`渲染第 ${i} 页时出错:`, error);
    }
  }
  
  totalHeight = currentTop;
  viewportHeight = pdfContainer.value.clientHeight;
};

const renderThumbnails = async () => {
  thumbnailRefs.value = [];
  
  for (let i = 1; i <= totalPages.value; i++) {
    try {
      const page = await pdfDoc.getPage(i);
      const viewport = page.getViewport({ scale: 0.15 });
      
      // 等待DOM更新
      await nextTick();
      
      if (thumbnailRefs.value[i-1]) {
        const canvas:any = thumbnailRefs.value[i-1];
        const context = canvas.getContext('2d');
        
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        
        await page.render({
          canvasContext: context,
          viewport: viewport
        }).promise;
      }
    } catch (error) {
      console.error(`渲染第 ${i} 页缩略图时出错:`, error);
    }
  }
};

const jumpToPage = (page:number) => {
  if (pageHeights.length >= page) {
    const pageInfo = pageHeights[page - 1];
    pdfContainer.value.scrollTo({
      top: pageInfo.top,
      behavior: 'smooth'
    });
  }
};

const toggleThumbnails = () => {
  showThumbnails.value = !showThumbnails.value;
};

const zoomIn = () => {
  scale.value = Math.min(scale.value + 0.1, 2.0);
  renderAllPages();
};

const zoomOut = () => {
  scale.value = Math.max(scale.value - 0.1, 0.5);
  renderAllPages();
};

// 新增：打印功能
const printPdf = () => {
  // 保存当前状态
  const originalScale = scale.value;
  const originalShowThumbnails = showThumbnails.value;
  
  // 创建打印样式
  const printStyle = document.createElement('style');
  printStyle.textContent = `
    @media print {
      body * {
        visibility: hidden;
      }
      .pdf-pages-container, .pdf-pages-container * {
        visibility: visible;
      }
      .pdf-pages-container {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        overflow: visible !important;
      }
      .pdf-page {
        page-break-inside: avoid;
        margin-bottom: 15mm !important;
      }
      .page-number {
        display: block !important;
      }
    }
  `;
  document.head.appendChild(printStyle);
  
  // 调整为适合打印的缩放比例
  scale.value = 1.0; // 设置为100%缩放
  showThumbnails.value = false; // 隐藏缩略图
  
  // 重新渲染页面以应用新的缩放比例
  renderAllPages().then(() => {
    // 等待渲染完成后调用打印
    setTimeout(() => {
      window.print();
      
      // 打印完成后恢复原始状态
      scale.value = originalScale;
      showThumbnails.value = originalShowThumbnails;
      renderAllPages();
      
      // 移除打印样式
      document.head.removeChild(printStyle);
    }, 500);
  });
};

const handleScroll = () => {
  if (!pdfContainer.value || pageHeights.length === 0) return;
  
  const scrollTop = pdfContainer.value.scrollTop;
  
  // 计算当前页
  for (let i = 0; i < pageHeights.length; i++) {
    const pageInfo = pageHeights[i];
    if (scrollTop >= pageInfo.top && scrollTop < pageInfo.top + pageInfo.height) {
      currentPage.value = pageInfo.page;
      break;
    }
  }
  
  // 计算滚动进度
  scrollProgress.value = Math.min(100, Math.max(0, Math.round((scrollTop / (totalHeight - viewportHeight)) * 100)));
};

// 模拟Vue的nextTick
const nextTick = () => {
  return new Promise(resolve => setTimeout(resolve, 0));
};

onMounted(() => {
  loadPdf();
});
</script>
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}


.container {
    max-width: 1200px;
    width: 100%;
    margin: 0 auto;
}

header {
    text-align: center;
    margin-bottom: 30px;
    color: white;
    padding: 20px;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

header h1 {
    font-size: 2.5rem;
    margin-bottom: 10px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

header p {
    font-size: 1.2rem;
    opacity: 0.9;
    max-width: 700px;
    margin: 0 auto;
}

.pdf-viewer-container {
    background: white;
    border-radius: 15px;
    box-shadow: 0 15px 50px rgba(0, 0, 0, 0.4);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 95vh;
}

.pdf-viewer {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 15px;
    background: #f8f9fa;
}

.viewer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background: #2c3e50;
    color: white;
    border-radius: 10px 10px 0 0;
}

.document-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.document-info i {
    font-size: 1.2rem;
    color: #42b983;
}

.controls {
    display: flex;
    gap: 10px;
}

.control-btn {
    background: #3498db;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.3s;
}

.control-btn:hover {
    background: #2980b9;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.control-btn:disabled {
    background: #95a5a6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

.zoom-controls {
    display: flex;
    gap: 5px;
    margin-left: 15px;
}

.zoom-btn {
    background: #34495e;
    color: white;
    border: none;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
}

.zoom-btn:hover {
    background: #2c3e50;
    transform: scale(1.1);
}

.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
    gap: 15px;
    margin-top: 15px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.thumbnails {
    width: 120px;
    overflow-y: auto;
    padding: 10px;
    background: #ecf0f1;
    border-radius: 8px;
    transition: all 0.3s;
}

.thumbnails.hidden {
    width: 0;
    padding: 0;
    overflow: hidden;
}

.thumbnail-item {
    margin-bottom: 15px;
    cursor: pointer;
    border: 2px solid transparent;
    border-radius: 5px;
    overflow: hidden;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
}

.thumbnail-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.thumbnail-item.active {
    border-color: #e74c3c;
    box-shadow: 0 0 0 3px rgba(231, 76, 60, 0.3);
}

.thumbnail-item canvas {
    width: 100%;
    height: auto;
    background: white;
    display: block;
}

.pdf-pages-container {
    flex: 1;
    overflow-y: auto;
    position: relative;
    background: #e0e0e0;
    border-radius: 8px;
}

.pdf-page {
    margin: 0 auto 20px;
    background: white;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    position: relative;
    overflow: hidden;
}

.page-number {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(231, 76, 60, 0.8);
    color: white;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 0.9rem;
    z-index: 10;
}

.scroll-indicator {
    position: fixed;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(44, 62, 80, 0.9);
    color: white;
    padding: 10px 20px;
    border-radius: 30px;
    display: flex;
    align-items: center;
    gap: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    z-index: 100;
}

.progress-container {
    height: 6px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 3px;
    flex: 1;
    max-width: 200px;
    overflow: hidden;
}

.progress-bar {
    height: 100%;
    background: #e74c3c;
    border-radius: 3px;
    transition: width 0.2s;
}

.status-bar {
    display: flex;
    justify-content: space-between;
    padding: 10px 15px;
    background: #2c3e50;
    color: white;
    border-radius: 0 0 10px 10px;
    font-size: 0.9rem;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 100;
    border-radius: 10px;
}

.spinner {
    width: 50px;
    height: 50px;
    border: 5px solid rgba(52, 152, 219, 0.3);
    border-radius: 50%;
    border-top-color: #3498db;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.loading-text {
    font-size: 1.2rem;
    color: #2c3e50;
    font-weight: bold;
}

.features {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-top: 30px;
    color: white;
}

.feature-card {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    backdrop-filter: blur(5px);
}

.feature-card h3 {
    font-size: 1.5rem;
    margin-bottom: 15px;
    color: #f1c40f;
    display: flex;
    align-items: center;
    gap: 10px;
}

.feature-card ul {
    padding-left: 20px;
}

.feature-card li {
    margin-bottom: 8px;
    line-height: 1.5;
}

@media (max-width: 768px) {
    .main-content {
        flex-direction: column;
    }
    
    .thumbnails {
        width: 100%;
        height: 150px;
        display: flex;
        overflow-x: auto;
        overflow-y: hidden;
        padding: 10px;
    }
    
    .thumbnails.hidden {
        height: 0;
        padding: 0;
    }
    
    .thumbnail-item {
        margin-right: 10px;
        margin-bottom: 0;
        flex: 0 0 auto;
        width: 80px;
    }
    
    header h1 {
        font-size: 2rem;
    }
}
</style>